﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Messaging;
using GalaSoft.MvvmLight.Command;
using SkyShell.Model;
using Coronox.SkyShell;
using System.IO;
using System.Threading.Tasks;
using GalaSoft.MvvmLight.Threading;
using System.Diagnostics;
using System.Windows;
using System.Text.RegularExpressions;

namespace SkyShell.ViewModel
{
    public class ShareContentViewModel : ViewModelBase
    {



        private bool _isBusy;
        public bool IsBusy
        {
            get
            {
                return _isBusy;
            }
            set
            {
                _isBusy = value;

                RaisePropertyChanged("IsBusy");
                //_createReadonlyLink.RaiseCanExecuteChanged();
                //_createEditableLink.RaiseCanExecuteChanged();
                //_shareByEmail.RaiseCanExecuteChanged();
            }
        }

        private string _shareLink;
        public string ShareLink
        {
            get
            {
                return _shareLink;
            }
            set
            {
                _shareLink = value;
                RaisePropertyChanged("ShareLink");
            }
        }

        private string _mailtTo;
        public string MailTo
        {
            get
            {
                return _mailtTo;
            }
            set
            {
                _mailtTo = value;
                RaisePropertyChanged("MailTo");
                //_shareByEmail.RaiseCanExecuteChanged();
            }
        }

        private bool _emailEditableShare;
        public bool EmailEditableShare
        {
            get
            {
                return _emailEditableShare;
            }
            set
            {
                _emailEditableShare = value;
                RaisePropertyChanged("EmailEditableShare");
            }
        }


        private string _personalMessage;
        public string PersonalMessage
        {
            get
            {
                return _personalMessage;
            }
            set
            {
                _personalMessage = value;
                RaisePropertyChanged("PersonalMessage");
            }
        }


        private bool _rememberLogin = true;

        /// <summary>
        /// Sets and gets the RememberLogin property.
        /// Changes to that property's value raise the PropertyChanged event. 
        /// </summary>
        public bool RememberLogin
        {
            get
            {
                _rememberLogin = SkyDriveAction.GetRegRememberLogin();
                return _rememberLogin;
            }

            set
            {
                if (_rememberLogin == value)
                {
                    return;
                }

                RaisePropertyChanging(() => RememberLogin);
                SkyDriveAction.SetRegRememberLogin(value);
                _rememberLogin = value;
                RaisePropertyChanged(() => RememberLogin);
            }
        }



        string _User = "Somebody";


        private string _localSkyDrivePath = string.Empty;

        /// <summary>
        /// Sets and gets the LocalSkyDrivePath property.
        /// Changes to that property's value raise the PropertyChanged event. 
        /// </summary>
        public string LocalSkyDrivePath
        {
            get
            {
                return _localSkyDrivePath;
            }

            set
            {
                if (_localSkyDrivePath == value)
                {
                    return;
                }
                _localSkyDrivePath = value;
                RaisePropertyChanged(() => LocalSkyDrivePath);
            }
        }

        private string _folderName;
        public string FolderName
        {
            get
            {
                return _folderName;
            }
            set
            {
                _folderName = value;
                RaisePropertyChanged("FolderName");
            }
        }



        private Uri _authUrl;
        public Uri AuthUrl
        {
            get
            {
                return _authUrl;
            }
            set
            {
                _authUrl = value;
                RaisePropertyChanged("AuthUrl");
            }
        }

        private string _readonlySharedLink = string.Empty;

        /// <summary>
        /// Sets and gets the SharedSkyDriveUrl property.
        /// Changes to that property's value raise the PropertyChanged event. 
        /// </summary>
        public string ReadonlySharedLink
        {
            get
            {
                return _readonlySharedLink;
            }

            set
            {
                if (_readonlySharedLink == value)
                {
                    return;
                }

                _readonlySharedLink = value;
                RaisePropertyChanged(() => ReadonlySharedLink);
                //DispatcherHelper.CheckBeginInvokeOnUI(() =>
                //    {
                //        _sharedByClipboard.RaiseCanExecuteChanged();
                //        _sharedByMail.RaiseCanExecuteChanged();
                //    });
            }
        }


        private string _editableSharedLink;
        public string EditableSharedLink
        {
            get
            {
                return _editableSharedLink;
            }
            set
            {
                _editableSharedLink = value;
                RaisePropertyChanged("EditableSharedLink");
            }
        }



        public ShareContentViewModel()
        {

            //cut and paste this line to your ctor
            _accessAccepted = new RelayCommand<Uri>(ExecAccessAccepted, CanAccessAccepted);
            //cut and paste this line to your ctor
            //_createReadonlyLink = new RelayCommand(ExecCreateReadonlyLink, CanCreateReadonlyLink);
            ////cut and paste this line to your ctor
            //_createEditableLink = new RelayCommand(ExecCreateEditableLink, CanCreateEditableLink);
            ////cut and paste this line to your ctor
            //_copyToClipboard = new RelayCommand<string>(ExecCopyToClipboard, CanCopyToClipboard);
            //cut and paste this line to your ctor
            _done = new RelayCommand(ExecDone, CanDone);
            //cut and paste this line to your ctor
            //_shareByEmail = new RelayCommand(ExecShareByEmail, CanShareByEmail);
            //cut and paste this line to your ctor
            //_getShareLink = new RelayCommand(ExecGetShareLink, CanGetShareLink);



            if (IsInDesignMode)
            {
                FolderName = "Some Folder";
            }
            _readonlySharedLink = string.Empty;
            _editableSharedLink = string.Empty;
        }




        private RelayCommand<Uri> _accessAccepted;
        public RelayCommand<Uri> AccessAccepted
        {
            get
            {
                return _accessAccepted;
            }
        }

        /// <summary>
        /// Checks whether the AccessAccepted command is executable
        /// </summary>
        private bool CanAccessAccepted(Uri uri)
        {
            return true;
        }



        private bool _authorizationPending = false;
        private bool _isAuthorized = false;
   
        /// <summary>
        /// Executes the AccessAccepted command 
        /// </summary>
        private void ExecAccessAccepted(Uri uri)
        {
          
            _authorizationPending = true;
           // Messenger.Default.Send<NotificationMessage<NavigationTargets>>(new NotificationMessage<NavigationTargets>(NavigationTargets.Share, null));
            IsBusy = true;
            Task t = new Task(() =>
                     {
                         System.Threading.Thread.Sleep(500);
                         if (uri.AbsoluteUri.Contains("code="))
                         {


                             SkyDriveAction.AuthCode = Regex.Split(uri.AbsoluteUri, "code=")[1];
                             string token = SkyDriveAction.GetAccessTokenAndRefreshToken();
                             if (token != null && token.Length > 0)
                             {
                                 //good to go
                                 _authorizationPending = false;
                                 CreateShareLink();
                             }
                             else
                             {
                                 DispatcherHelper.CheckBeginInvokeOnUI(() =>
                               {
                                   IsBusy = false;
                                   MessageBox.Show("Couldn't receive access token.");
                                   App.Current.MainWindow.Close();
                               });
                             }
                    


                         }
                         else
                         {
                             DispatcherHelper.CheckBeginInvokeOnUI(() =>
                               {
                                   MessageBox.Show("Couldn't receive access code.");
                                   App.Current.MainWindow.Close();
                               });
                         }
                     });
            t.Start();
        }

        private void CreateShareLink()
        {
            IsBusy = true;
            Task t = new Task(() =>
                   {
                       SkyDriveDirectoryInfo folder = SkyDriveAction.GetSkyDriveFolder(LocalSkyDrivePath);
                       string[] idArr = folder.ID.Split(".".ToCharArray());
                       string cid = idArr[1];
                       string id = idArr[2];
                       DispatcherHelper.CheckBeginInvokeOnUI(() =>
                       {
                           IsBusy = false;
                           //https://skydrive.live.com/?cid=d9969a7a68650af6&id=D9969A7A68650AF6%2127032&action=Share
                           ShareLink = string.Format("https://skydrive.live.com/?cid={0}&id={1}&action=Share", cid, id);

                       });
                   });
            t.Start();
        }




        public void Load()
        {
            if (Environment.GetCommandLineArgs().Length > 2)
            {
                string folderName = Environment.GetCommandLineArgs()[2];
                DirectoryInfo di = new DirectoryInfo(folderName);
                FolderName = di.Name;
                LocalSkyDrivePath = di.FullName;
                if (Environment.GetCommandLineArgs()[1] == "/sharecontent")
                {
                    Task t = new Task(() =>
                    {
                        //this.BusyAnimation = "Visible";
                        if (SkyDriveAction.RenewRefreshToken())
                        {
                            // GetSharedSkyDriveUrl();
                            CreateShareLink();
                        }
                        else
                        {
                            if (!_authorizationPending)
                            {
                                //send the user to authentication
                                DispatcherHelper.CheckBeginInvokeOnUI(() =>
                                    {
                                        AuthUrl = SkyDriveAction.SignInUrl;
                                    });
                              //  Messenger.Default.Send<NotificationMessage<NavigationTargets>>(new NotificationMessage<NavigationTargets>(NavigationTargets.Authenticate, null));
                            }
                        }
                    });

                    t.Start();
                }
            }
        }


        //private RelayCommand _createReadonlyLink;
        //public RelayCommand CreateReadonlyLink
        //{
        //    get
        //    {
        //        return _createReadonlyLink;
        //    }
        //}

        ///// <summary>
        ///// Checks whether the CreateReadonlyLink command is executable
        ///// </summary>
        //private bool CanCreateReadonlyLink()
        //{
        //    return !_isBusy;
        //}

        ///// <summary>
        ///// Executes the CreateReadonlyLink command 
        ///// </summary>
        //private void ExecCreateReadonlyLink()
        //{
        //    IsBusy = true;

        //    Task t = new Task(() =>
        //        {

        //            try
        //            {
        //                SkyDriveDirectoryInfo folder = SkyDriveAction.GetSkyDriveFolder(LocalSkyDrivePath);
        //                ReadonlySharedLink = SkyDriveAction.GetReadonlySharedLink(folder.ID);
        //                //_FolderName = folder.Name;
        //                var userinfo = SkyDriveAction.GetUserInfo();
        //                if (userinfo != null)
        //                    _User = userinfo["first_name"];
        //                else _User = "Somebody";
        //            }
        //            catch
        //            {
        //                MessageBox.Show("Creating the shared link failed.", "ERROR", MessageBoxButton.OK);
        //            }
        //            finally
        //            {
        //                DispatcherHelper.CheckBeginInvokeOnUI(() =>
        //                {
        //                    IsBusy = false;
        //                });
        //            }
        //        });
        //    t.Start();
        //}



        //private RelayCommand _createEditableLink;
        //public RelayCommand CreateEditableLink
        //{
        //    get
        //    {
        //        return _createEditableLink;
        //    }
        //}

        ///// <summary>
        ///// Checks whether the CreateEditableLink command is executable
        ///// </summary>
        //private bool CanCreateEditableLink()
        //{
        //    return !_isBusy;
        //}

        ///// <summary>
        ///// Executes the CreateEditableLink command 
        ///// </summary>
        //private void ExecCreateEditableLink()
        //{

        //    // SkyDriveAction.GetEmails();

        //    IsBusy = true;

        //    Task t = new Task(() =>
        //    {
        //        try
        //        {
        //            SkyDriveDirectoryInfo folder = SkyDriveAction.GetSkyDriveFolder(LocalSkyDrivePath);
        //            EditableSharedLink = SkyDriveAction.GetEditableSharedLink(folder.ID);
        //            //_FolderName = folder.Name;
        //            var userinfo = SkyDriveAction.GetUserInfo();
        //            if (userinfo != null)
        //                _User = userinfo["first_name"];
        //            else _User = "Somebody";
        //        }
        //        catch (Exception ex)
        //        {
        //            MessageBox.Show("Creating the shared link failed.", "ERROR", MessageBoxButton.OK);
        //        }
        //        finally
        //        {
        //            DispatcherHelper.CheckBeginInvokeOnUI(() =>
        //            {
        //                IsBusy = false;
        //            });
        //        }
        //    });
        //    t.Start();
        //}


        //private RelayCommand<string> _copyToClipboard;
        //public RelayCommand<string> CopyToClipboard
        //{
        //    get
        //    {
        //        return _copyToClipboard;
        //    }
        //}

        ///// <summary>
        ///// Checks whether the CopyToClipboard command is executable
        ///// </summary>
        //private bool CanCopyToClipboard(string val)
        //{
        //    return !string.IsNullOrEmpty(val);
        //}

        ///// <summary>
        ///// Executes the CopyToClipboard command 
        ///// </summary>
        //private void ExecCopyToClipboard(string val)
        //{
        //    if (val == "readonly")
        //        Clipboard.SetText(this.ReadonlySharedLink);
        //    if (val == "editable")
        //        Clipboard.SetText(this.EditableSharedLink);
        //}





        private RelayCommand _done;
        public RelayCommand Done
        {
            get
            {
                return _done;
            }
        }

        /// <summary>
        /// Checks whether the Done command is executable
        /// </summary>
        private bool CanDone()
        {
            return true;
        }

        /// <summary>
        /// Executes the Done command 
        /// </summary>
        private void ExecDone()
        {
            App.Current.MainWindow.Close();
        }



        //private RelayCommand _shareByEmail;
        //public RelayCommand ShareByEmail
        //{
        //    get
        //    {
        //        return _shareByEmail;
        //    }
        //}

        ///// <summary>
        ///// Checks whether the ShareByEmail command is executable
        ///// </summary>
        //private bool CanShareByEmail()
        //{
        //    return !IsBusy && !string.IsNullOrEmpty(_mailtTo);
        //}

        ///// <summary>
        ///// Executes the ShareByEmail command 
        ///// </summary>
        //private void ExecShareByEmail()
        //{
        //    IsBusy = true;
        //    Task t = new Task(() =>
        //        {
        //            string link;
        //            if (_emailEditableShare)
        //            {
        //                SkyDriveDirectoryInfo folder = SkyDriveAction.GetSkyDriveFolder(LocalSkyDrivePath);
        //                link = SkyDriveAction.GetEditableSharedLink(folder.ID);
        //                var userinfo = SkyDriveAction.GetUserInfo();
        //                if (userinfo != null)
        //                    _User = userinfo["first_name"];
        //                else _User = "Somebody";
        //            }
        //            else
        //            {
        //                SkyDriveDirectoryInfo folder = SkyDriveAction.GetSkyDriveFolder(LocalSkyDrivePath);
        //                link = SkyDriveAction.GetReadonlySharedLink(folder.ID);
        //                var userinfo = SkyDriveAction.GetUserInfo();
        //                if (userinfo != null)
        //                    _User = userinfo["first_name"];
        //                else _User = "Somebody";
        //            }
               
        //            string subject = string.Format("{0} shared a folder with you", _User).ToMailto();
        //            string cc = " ";
        //            string bcc = " ";

        //            IsBusy = false;
        //            string body = String.Format("{0} %0D%0A%0D%0AThe following folder was shared with you: {1} [{2}].%0D%0AShared via SkyShellEx", _personalMessage, _folderName, link).ToMailto();
        //            string mail = String.Format("mailto:{0}?subject={1}&cc={2}&bcc={3}&body={4}", MailTo, subject, cc, bcc, body);
        //            try
        //            {
        //                Process.Start(mail);
        //            }
        //            catch (Exception ex)
        //            {
        //                MessageBox.Show("No email client associated with mailto: protocol.");
        //            }
        //            finally
        //            {
        //                DispatcherHelper.CheckBeginInvokeOnUI(() =>
        //                    {
        //                        App.Current.MainWindow.Close();
        //                    });
        //            }
        //        });
        //    t.Start();
        //}

        




        //private RelayCommand<System.Windows.Navigation.NavigationEventArgs> _ApplyAccessToken;

        ///// <summary>
        ///// Gets the AccessToken.
        ///// </summary>
        //public RelayCommand<System.Windows.Navigation.NavigationEventArgs> ApplyAccessToken
        //{
        //    get
        //    {
        //        return _ApplyAccessToken ?? (_ApplyAccessToken = new RelayCommand<System.Windows.Navigation.NavigationEventArgs>((e) => CommandWithAParameter(e)));
        //    }
        //}


        //private void CommandWithAParameter(System.Windows.Navigation.NavigationEventArgs e)
        //{
        //    Task t = new Task(() =>
        //    {
        //        if (e.Uri.AbsoluteUri.Contains("code="))
        //        {


        //            // Restore Window Height
        //            Messenger.Default.Send(new Tuple<string, bool>("IsLoginBrowserVisible", false));
        //            Messenger.Default.Send(new Tuple<string, int>("Restore Window Height", 0));

        //            SkyDriveAction.AuthCode = Regex.Split(e.Uri.AbsoluteUri, "code=")[1];


        //            if (SkyDriveAction.GetAccessTokenAndRefreshToken().Length > 0)
        //            {
        //                //GetSharedSkyDriveUrl();
        //            }
        //            else
        //            {
        //               // this.BusyAnimation = "Hidden";
        //            }
        //        }

        //    });

        //    t.Start();
        //}






    }
}
